package com.bestv.search.management.command;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.dataSource.DataSourceKeyUtil;
import com.bestv.search.common.model.History;
import com.bestv.search.common.service.HistoryManager;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Michael Wang
 */

// $Id: HistoryCommand.java 116 2012-09-03 01:56:56Z wbwang $
public class HistoryCommand {

    private static final int DEFAULT_HISTORY_LIMIT = 10;
    Logger logger = Logger.getLogger(HistoryCommand.class);
    private HistoryManager historyManager;

    public void saveHistories(List<History> histories, String siteCode) {
        DataSourceKey key = DataSourceKeyUtil.convert(siteCode);
        List<History> result = new ArrayList<History>();
        for (History hisElem : histories) {
            History history = historyManager.getHistoryByUserId(key, hisElem.getUserId());
            if (history == null) {
                result.add(hisElem);
            } else {
                Date dbTime = history.getTime();
                Date now = hisElem.getTime();
                if (dbTime.getTime() - now.getTime() > 0)
                    continue;
                history.setTime(now);
                String oriHistory = history.getHistory();
                String newHistory = hisElem.getHistory() + "_" + oriHistory;
                String[] hisArr = newHistory.split("_");
                int n = Math.min(hisArr.length, DEFAULT_HISTORY_LIMIT);
                newHistory = "";
                for (int i = 0; i < n; i++) {
                    if (i > 0 && hisArr[i].equals(hisArr[i - 1]))
                        continue;
                    newHistory += hisArr[i] + (i != n - 1 ? "_" : "");
                }
                if (newHistory.endsWith("_"))
                    newHistory = newHistory.substring(0, newHistory.lastIndexOf("_"));
                history.setHistory(newHistory);
                result.add(history);
            }
        }
        historyManager.saveHistoryList(key, result);
    }

    public HistoryManager getHistoryManager() {
        return historyManager;
    }

    public void setHistoryManager(HistoryManager historyManager) {
        this.historyManager = historyManager;
    }

}
